package com.sunshine.lnuplus.adapter

import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Button
import com.sunshine.lnuplus.R
import com.sunshine.lnuplus.callback.PickWeeksCallBack
import com.sunshine.lnuplus.model.InitData
import kotlin.collections.ArrayList

class PickWeeksGridViewAdapter(
    private val context: Context,
    weeks: List<Int>?,
    private val callBack: PickWeeksCallBack
) : BaseAdapter(){

    private var weekList = ArrayList<Int>()

    init {
        if(weeks == null){
            for(i in 1..InitData.lessonStyle.weekCount){
                weekList.add(i)
            }
        } else {
            weekList = (weeks as ArrayList<Int>?)!!
        }
        callBack.callBack(weekList)
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        var convertView = convertView
        convertView = LayoutInflater.from(context).inflate(R.layout.item_pick_week_gril_view, parent, false)
        val button = convertView.findViewById<Button>(R.id.pick_week_button)
        button.text = "${position + 1}"

        when {
            weekList.contains(position + 1) -> {
                button.setBackgroundDrawable(context.resources.getDrawable(R.drawable.ripple_yellow_bg))
                button.setTextColor(Color.WHITE)
            }
            else -> {
                button.setBackgroundDrawable(context.resources.getDrawable(R.drawable.ripple_bg))
                button.setTextColor(Color.BLACK)
            }
        }

        button.setOnClickListener {
            if(weekList.contains(position + 1)){
                weekList.remove(position + 1)
                button.setBackgroundDrawable(context.resources.getDrawable(R.drawable.ripple_bg))
                button.setTextColor(Color.BLACK)
                callBack.callBack(weekList)
            } else {
                weekList.add(position + 1)
                weekList.sort()//从小到大排序
                button.setBackgroundDrawable(context.resources.getDrawable(R.drawable.ripple_yellow_bg))
                button.setTextColor(Color.WHITE)
                callBack.callBack(weekList)
            }
        }
        return convertView
    }

    override fun getItem(position: Int): Any {
        return position + 1
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getCount(): Int {
        return InitData.lessonStyle.weekCount
    }

}